<script setup lang="ts">
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox, ElButton } from "element-plus";
import Searchbox from "@/views/components/searchbox/Searchbox.vue";
import {
  getAlertLogPageListApi,
  deleteAlertLogApi,
  batchDeleteAlertLogApi,
  batchHandleAlertLogApi,
  AlertLogModel
} from "@/api/alerts/alertLog";
import { pageSizeOptions } from "@/utils/appCommon/appCommonOptions/app";
import { useI18n } from "vue-i18n";
import { useLogic } from "@/views/system/user/logic/logic";
import AlertLogHandle from "./component/handle.vue";

defineOptions({
  name: "alert-log"
});

const i18n = useI18n();
const { t } = i18n;
const pageSizeOps = ref(pageSizeOptions);

// 部门树数据
const { deptTreeList, getDeptTree } = useLogic();
onMounted(async () => {
  await getDeptTree();
});

// 搜索参数
const searchDefault = {
  deptId:0,
  level: undefined,
  bindTo: undefined,
  handleStatus: undefined,
  timeRange: [],
  pageSize: 10,
  page: 1,
};

const searchParams = ref(Object.assign({}, searchDefault));

// 搜索字段配置
const searchFields = ref([
  {
    prop: "sceneId",
    name: t("alerts.alertLogPage.search.sceneId"),
    type: "input",
    placeholder: "",
  },
  {
    prop: "level",
    name: t("alerts.alertLogPage.search.level"),
    type: "select",
    formOptions: [
      { val: 1, label: "1" },
      { val: 2, label: "2" },
      { val: 3, label: "3" },
      { val: 4, label: "4" },
      { val: 5, label: "5" },
    ]
  },
  {
    prop: "bindTo",
    name: t("alerts.alertLogPage.search.bindTo"),
    type: "select",
    formOptions: [
      { val: 0, label: t("alerts.alertLogPage.bindTo.device") },
      { val: 1, label: t("alerts.alertLogPage.bindTo.group") }
    ]
  },
  {
    prop: "handleStatus",
    name: t("alerts.alertLogPage.search.handleStatus"),
    type: "select",
    formOptions: [
      { val: 0, label: t("alerts.alertLogPage.status.unhandled") },
      { val: 1, label: t("alerts.alertLogPage.status.handling") },
      { val: 2, label: t("alerts.alertLogPage.status.completed") }
    ]
  },
  {
    prop: "deptId",
    name: t("alerts.peoplePage.table.deptId"),
    type: "cascader",
    cascaderOptions: deptTreeList,
    ops: {
      valueField: "id",
      labelField: "name",
      emitPath: false,
      checkStrictly: true
    }
  },
  {
    prop: "timeRange",
    name: t("buttons.timeRange"),
    type: "datetimeRange",
    clearable: true,
    isHidden: false,
  },
]);

// 表格数据
const tableData = ref<AlertLogModel[]>([]);
const total = ref(0);
const loading = ref(false);
const selectedRows = ref<AlertLogModel[]>([]);

// 处理对话框
const handleDialogVisible = ref(false);
const currentLog = ref<AlertLogModel | null>(null);
// 批量处理对话框
const batchHandleDialogVisible = ref(false);
const selectedAlertLogIds = ref<number[]>([]);

// 加载数据
const loadData = async () => {
  loading.value = true;
  try {
    const params = { ...searchParams.value };
    const response = await getAlertLogPageListApi(params);
    if (response.code === 0) {
      tableData.value = response.data?.list || [];
      total.value = response.data?.total || 0;
    } else {
      ElMessage.error(response.msg || t('alerts.alertLogPage.getFailed'));
    }
  } catch (error) {
    total.value = 0;
    tableData.value = [];
    ElMessage.error(t('alerts.alertLogPage.getFailed'));
    console.error("Failed to load alert log list:", error);
  } finally {
    loading.value = false;
  }
};

// 初始加载
onMounted(() => {
  loadData();
});

// 分页变化处理
const handlePaginationSizeChange = (pageSize: number) => {
  searchParams.value.pageSize = pageSize;
  loadData();
};
const handlePaginationPageChange = (page: number) => {
  searchParams.value.page = page;
  loadData();
};

// 搜索处理
const handleChange = (e: any) => {
  Object.keys(e).forEach(key => {
    searchParams.value[key] = e[key];
  });
};

const handleSearch = async (e: any) => {
  searchParams.value.page = 1;
  Object.keys(e).forEach(key => {
    searchParams.value[key] = e[key];
  });
  await loadData();
};

const handleReset = (e: any) => {
  searchParams.value = Object.assign({}, searchDefault);
};

// 刷新列表
const refreshList = () => {
  loadData();
};

// 删除操作
const handleDelete = async (id: number) => {
  try {
    await ElMessageBox.confirm(
      t('alerts.alertLogPage.deleteConfirm'),
      t('buttons.confirm'),
      {
        confirmButtonText: t('buttons.confirm'),
        cancelButtonText: t('buttons.cancel'),
        type: 'warning'
      }
    );

    const response = await deleteAlertLogApi(id);
    if (response.code === 0) {
      ElMessage.success(t('alerts.alertLogPage.deleteSuccess'));
      refreshList();
    } else {
      ElMessage.error(response.msg || t('alerts.alertLogPage.deleteFailed'));
    }
  } catch (error: any) {
    if (error.name !== 'cancel') {
      ElMessage.error(t('alerts.alertLogPage.deleteFailed'));
    }
  }
};

// 批量删除
const handleSelectionChange = (rows: AlertLogModel[]) => {
  selectedRows.value = rows;
};

const handleBatchDelete = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning(t('alerts.alertLogPage.selectRecordFirst'));
    return;
  }

  try {
    await ElMessageBox.confirm(
      t('alerts.alertLogPage.batchDeleteConfirm', { count: selectedRows.value.length }),
      t('buttons.confirm'),
      {
        confirmButtonText: t('buttons.confirm'),
        cancelButtonText: t('buttons.cancel'),
        type: 'warning'
      }
    );

    const ids = selectedRows.value.map(row => row.id);
    const response = await batchDeleteAlertLogApi(ids);

    if (response.code === 0) {
      ElMessage.success(t('alerts.alertLogPage.batchDeleteSuccess'));
      await loadData();
      selectedRows.value = [];
    } else {
      ElMessage.error(response.msg || t('alerts.alertLogPage.batchDeleteFailed'));
    }
  } catch (error: any) {
    if (error.name !== 'cancel') {
      ElMessage.error(t('alerts.alertLogPage.batchDeleteFailed'));
    }
  }
};

// 打开处理对话框
const openHandleDialog = (row: AlertLogModel) => {
  currentLog.value = { ...row };
  handleDialogVisible.value = true;
};

// 处理成功后的回调
const handleSuccessCallback = () => {
  refreshList();
};

// 批量处理成功后的回调
const batchHandleSuccessCallback = () => {
  refreshList();
  selectedRows.value = [];
};

// 批量处理
const handleBatchHandle = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning(t('alerts.alertLogPage.selectRecordFirst'));
    return;
  }

  // 检查是否都可以处理（未处理或处理中的记录）
  const canHandle = selectedRows.value.every(row => row.handleStatus === 0 || row.handleStatus === 1);
  if (!canHandle) {
    ElMessage.warning('只能处理未处理或处理中的告警记录');
    return;
  }

  // 设置选中的ID并打开批量处理对话框
  selectedAlertLogIds.value = selectedRows.value.map(row => row.id);
  batchHandleDialogVisible.value = true;
};

// 格式化状态显示
const formatHandleStatus = (status: number) => {
  switch (status) {
    case 0:
      return t('alerts.alertLogPage.status.unhandled');
    case 1:
      return t('alerts.alertLogPage.status.handling');
    case 2:
      return t('alerts.alertLogPage.status.completed');
    default:
      return status;
  }
};

// 格式化绑定对象显示
const formatBindTo = (bindTo: number) => {
  return bindTo === 0 ? t('alerts.alertLogPage.bindTo.device') : t('alerts.alertLogPage.bindTo.group');
};
</script>

<template>
  <el-card shadow="never">
    <template #header>
      <div class="search-area">
        <Searchbox
          :fields="searchFields"
          :initialValues="searchParams"
          :maxVisibleFields="3"
          @change="handleChange"
          @search="handleSearch"
          @reset="handleReset"
        />
      </div>
    </template>
    <div class="button-area">
      <el-button type="primary" icon="Check" @click="handleBatchHandle" :disabled="selectedRows.length === 0">
        {{t('buttons.handle')}}
      </el-button>
      <el-button type="danger" icon="Delete" @click="handleBatchDelete" :disabled="selectedRows.length === 0">
        {{ t('buttons.batchDelete') }}
      </el-button>
    </div>

    <el-table
      :data="tableData"
      v-loading="loading"
      border
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" :label="t('alerts.alertLogPage.table.id')" width="80" />
      <el-table-column prop="sceneName" :label="t('alerts.alertLogPage.table.sceneId')" width="100" />
      <el-table-column prop="level" :label="t('alerts.alertLogPage.table.level')" width="80" />
      <el-table-column prop="bindTo" :label="t('alerts.alertLogPage.table.bindTo')" width="100">
        <template #default="{ row }">
          {{ formatBindTo(row.bindTo) }}
        </template>
      </el-table-column>
      <el-table-column prop="bindId" :label="t('alerts.alertLogPage.table.bindId')" min-width="120" />
      <el-table-column prop="deptName" :label="t('alerts.alertLogPage.table.deptId')" width="100" />
      <el-table-column prop="handleStatus" :label="t('alerts.alertLogPage.table.handleStatus')" width="120">
        <template #default="{ row }">
          <span :class="{
            'status-unhandled': row.handleStatus === 0,
            'status-handling': row.handleStatus === 1,
            'status-completed': row.handleStatus === 2
          }">
            {{ formatHandleStatus(row.handleStatus) }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="handRemark" :label="t('alerts.alertLogPage.table.handRemark')" min-width="150" />
      <el-table-column prop="createdAt" :label="t('alerts.alertLogPage.table.createdAt')" width="180" />
      <el-table-column prop="handleTime" :label="t('alerts.alertLogPage.table.handleTime')" width="180" />
      <el-table-column :label="t('alerts.alertLogPage.table.operation')" width="180">
        <template #default="{ row }">
          <el-button
            v-if="row.handleStatus === 0 || row.handleStatus === 1"
            type="primary"
            size="small"
            @click="openHandleDialog(row)"
          >
            {{t('buttons.handle')}}
          </el-button>
          <el-button
            type="danger"
            size="small"
            @click="handleDelete(row.id)"
          >
            {{ t('buttons.delete') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-model:current-page="searchParams.page"
      v-model:page-size="searchParams.pageSize"
      :page-sizes="pageSizeOps"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handlePaginationSizeChange"
      @current-change="handlePaginationPageChange"
    />

    <!-- 处理告警组件同时支持单个和批量处理 -->
    <AlertLogHandle
      v-model:visible="handleDialogVisible"
      :alert-log="currentLog"
      :alert-log-ids="selectedAlertLogIds"
      @handle-success="handleSuccessCallback"
    />

  </el-card>
</template>

<style scoped lang="scss">
.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16px;
}

.button-area {
  margin: 16px 0;
  display: flex;
  justify-content: flex-start;
  gap: 10px;
}

.search-area {
  margin-bottom: 16px;
}

.status-unhandled {
  color: #f56c6c;
}

.status-handling {
  color: #e6a23c;
}

.status-completed {
  color: #67c23a;
}
</style>
